package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.geepi.base.DBUtil;

public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("doGet start...");
		request.setCharacterEncoding("UTF-8");
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String querySql = String.format("select * from account where account = '%s' and password = '%s';", account, password);
		
		int status = -1;
		String message = "";
		HashMap<String, String> param = new HashMap<>();

		DBUtil dbUtil = new DBUtil();
		boolean isOpen = dbUtil.open();
		if (isOpen == false) {
			status = 102;
			message = "数据库打开失败";
		} else {
			try {
				ResultSet resultSetCount = dbUtil.query(querySql);
				while (resultSetCount.next()) {
					String queryAccount = resultSetCount.getString("account");
					if (queryAccount == null || queryAccount.equals("")) {
						status = 100001;
						message = "用户名或密码错误";
					} else {
						status = 0;
						message = "验证成功";
						param.put("nick", resultSetCount.getString("nick"));
					}
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		Map<String, Object> tempParamsMap = new HashMap<String, Object>();
		tempParamsMap.put("status", status);
		tempParamsMap.put("msg", message);
		tempParamsMap.put("item", param);
		JSONObject jsonObject = null;		
		jsonObject = JSONObject.fromObject(tempParamsMap);



		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(jsonObject);
		out.flush(); // 必须有这行，不然页面不会显示
		out.close();


		System.out.println("doGet end...");
		super.doGet(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
		super.doPost(req, resp);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	

}
